package com.suncky.frame.account;

import android.text.TextUtils;

public class BaseAccountManager<T> {
    private final AccountStorage<T> preferenceAccountStorage;
    private final AccountStorage<T> memoryAccountStorage;

    public BaseAccountManager(Class<T> tClass) {
        memoryAccountStorage = new MemoryAccountStorage<>();
        preferenceAccountStorage = new PreferenceAccountStorage<>(tClass);
    }

    /**
     * 清除登录账户信息
     */
    public void clear() {
        clearAccount();
        clearToken();
    }

    /**
     * 是否已登录
     * @return
     */
    public boolean isLogin() {
        return isTokenAvailable();
    }

    /**
     * token是否可用
     * @return
     */
    public boolean isTokenAvailable() {
        String token = getToken();
        return !TextUtils.isEmpty(token);
    }

    public void saveToken(String token) {
        saveTokenToMemory(token);
        saveTokenToPreference(token);
    }

    public String getToken() {
        String token = getTokenFromMemory();
        if (TextUtils.isEmpty(token)) {
            token = getTokenFromPreference();
        }
        return token;
    }

    public void saveAccount(T account) {
        saveAccountToMemory(account);
        saveAccountToPreference(account);
    }

    public T getAccount() {
        T account = getAccountFromMemory();
        if (account == null) {
            account = getAccountFromPreference();
        }
        return account;
    }

    public void clearAccount() {
        clearAccountMemory();
        clearAccountPreference();
    }

    public void clearToken() {
        clearTokenMemory();
        clearTokenPreference();
    }

    public void saveAccountToPreference(T account) {
        preferenceAccountStorage.saveAccount(account);
    }

    public T getAccountFromPreference() {
        return preferenceAccountStorage.getAccount();
    }

    public void clearAccountPreference() {
        preferenceAccountStorage.removeAccount();
    }

    public void saveAccountToMemory(T account) {
        memoryAccountStorage.saveAccount(account);
    }

    public T getAccountFromMemory() {
        return memoryAccountStorage.getAccount();
    }

    public void clearAccountMemory() {
        memoryAccountStorage.removeAccount();
    }

    public String getTokenFromMemory() {
        return memoryAccountStorage.getToken();
    }

    public String getTokenFromPreference() {
        return preferenceAccountStorage.getToken();
    }

    public void saveTokenToMemory(String token) {
        memoryAccountStorage.saveToken(token);
    }

    public void saveTokenToPreference(String token) {
        preferenceAccountStorage.saveToken(token);
    }

    public void clearTokenMemory() {
        memoryAccountStorage.removeToken();
    }

    public void clearTokenPreference() {
        preferenceAccountStorage.removeToken();
    }
}
